package utils

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"encoding/hex"
	"errors"
	"fmt"
)

// AesEncrypt AES加密,CBC
// 注意：aes密钥key的长度必须为16，24，32个字符
func AesEncrypt(origData, key []byte) (string, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return "", err
	}

	blockSize := block.BlockSize()
	origData = PKCS7Padding(origData, blockSize)
	blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
	crypted := make([]byte, len(origData))
	blockMode.CryptBlocks(crypted, origData)

	return EncodeBase64(crypted), nil
}

// AesDecrypt AES解密
func AesDecrypt(baseStr string, key []byte) (origData []byte, aesErr error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}

	defer func() {
		if err := recover(); err != nil {
			aesErr = errors.New(fmt.Sprintf("AesDecrypt error: %s", err))
		}
	}()

	crypted, err := DecodeBase64(baseStr)
	if err != nil {
		return nil, errors.New("baseStr error")
	}

	blockSize := block.BlockSize()
	blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
	origData = make([]byte, len(crypted))
	blockMode.CryptBlocks(origData, crypted)
	origData = PKCS7UnPadding(origData)

	return origData, nil
}

// CBCEncrypt CBC加密
func CBCEncrypt(text string, key []byte, iv []byte) (string, error) {
	//生成cipher.Block 数据块
	block, err := aes.NewCipher(key)
	if err != nil {
		return "", err
	}
	//填充内容，如果不足16位字符
	blockSize := block.BlockSize()

	originData := PKCS7Padding([]byte(text), blockSize)
	//加密方式
	blockMode := cipher.NewCBCEncrypter(block, iv)
	//加密，输出到[]byte数组
	crypted := make([]byte, len(originData))
	blockMode.CryptBlocks(crypted, originData)

	return hex.EncodeToString(crypted), nil
}

// CBCDecrypt CBC解密
func CBCDecrypt(sign string, key, iv []byte) (string, error) {

	block, err := aes.NewCipher(key)
	if err != nil {
		return "", err
	}
	//if len(iv)%block.BlockSize() != 0 {
	//	return "", fmt.Errorf("Invalid iv length %d", block.BlockSize())
	//}
	ciphertext, err := hex.DecodeString(sign)
	if err != nil {
		return "", err
	}

	origin_data := make([]byte, len(ciphertext))
	mode := cipher.NewCBCDecrypter(block, iv)
	mode.CryptBlocks(origin_data, ciphertext)

	return string(PKCS7UnPadding(origin_data)), nil
}

// PKCS7Padding 填充加密块
func PKCS7Padding(ciphertext []byte, blockSize int) []byte {
	padding := blockSize - len(ciphertext)%blockSize
	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(ciphertext, padtext...)
}

// PKCS7UnPadding 清除加密块中填充字节
func PKCS7UnPadding(origData []byte) []byte {
	length := len(origData)
	unpadding := int(origData[length-1])
	return origData[:(length - unpadding)]
}
